package com.cgnpc.scp.manager.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.cgnpc.cuddemo.utils.IDHelper;
import com.cgnpc.framework.userinfo.CurrentUser;
import com.cgnpc.scp.common.bean.MyPageResult;
import com.cgnpc.scp.common.exception.ScpException;
import com.cgnpc.scp.common.pojo.UserInfo;
import com.cgnpc.scp.common.utils.MyPageResultUtil;
import com.cgnpc.scp.common.utils.StringUtil;
import com.cgnpc.scp.manager.mybatis.entity.ProcessInfo;
import com.cgnpc.scp.manager.mybatis.entity.ProcessVisit;
import com.cgnpc.scp.manager.mybatis.mapper.client.ProcessInfoMapper;
import com.cgnpc.scp.manager.mybatis.mapper.client.ProcessVisitMapper;
import com.cgnpc.scp.manager.service.IProcessInfoService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

/******************************
 * 用途说明: 流程应用列表
 * 作者姓名: chenshijie
 * 创建时间: 2020/08/06 23:18
 ******************************/
@Service
public class ProcessInfoServiceImpl implements IProcessInfoService {

    private static final Logger LOGGER = LoggerFactory.getLogger(ProcessInfoServiceImpl.class);

    @Autowired
    private ProcessInfoMapper processInfoMapper;

    @Autowired
    private ProcessVisitMapper processVisitMapper;

    @Autowired
    CurrentUser currentUser;

    /**********************************
     * 用途说明: 保存流程信息
     * 参数说明 processInfo
     * 返回值说明:
     ***********************************/
    @Override
    public int save(ProcessInfo processInfo) throws Exception {
        int updateRows = 0;

        try {
            processInfo.setId(IDHelper.uuid());
            processInfo.setCreateTime(new Date());
            UserInfo userinfo = currentUser.getCurrentUserDetail();
            processInfo.setCreateUser(userinfo.getUserId());
            processInfo.setCreateUserName(userinfo.getUserName());
            updateRows = processInfoMapper.insert(processInfo);
        } catch (Exception e) {
            LOGGER.error("save.error;", e);
            throw e;
        }

        return updateRows;
    }

    /**********************************
     * 用途说明: 更新流程信息
     * 参数说明 processInfo
     * 返回值说明:
     ***********************************/
    @Override
    public int update(ProcessInfo processInfo) throws Exception {
        if(StringUtil.isNullOrSpace(processInfo.getId())) {
            throw new ScpException("params errror.");
        }

        int updateRows = 0;

        try {
            processInfo.setCreateTime(new Date());
            UserInfo userinfo = currentUser.getCurrentUserDetail();
            processInfo.setLastUpdateUser(userinfo.getUserId());
            processInfo.setLastUpdateUserName(userinfo.getUserName());
            processInfo.setLastUpdateTime(new Date());
            updateRows = processInfoMapper.updateById(processInfo);
        } catch (Exception e) {
            LOGGER.error("update.error;", e);
            throw e;
        }

        return updateRows;
    }

    /**********************************
     * 用途说明: 分页查询流程信息
     * 参数说明 processInfo
     * 返回值说明:
     ***********************************/
    @Override
    public MyPageResult<ProcessInfo> loadByPaging(ProcessInfo processInfo) {
        // begin 分页开始
        // 第几页
        int pageNum = processInfo.getPageNum();
        // 每页的数量
        int pageSize = processInfo.getPageSize();
        // 创建Page对象，将pageNum，pageSize参数传入，必须位于数据库查询数据的语句之前，否则不生效
//        Page<ProcessInfo> queryPage = PageHelper.startPage(pageNum, pageSize);
//        Page<ProcessInfo> queryPage = new Page<>(pageNum, pageSize);
        Page<ProcessInfo> page = new Page<>(pageNum, pageSize);

        // mybatis查询方式
//        ProcessInfoExample processInfoExample = new ProcessInfoExample();
//        ProcessInfoExample.Criteria queryExampleCriteria = processInfoExample.createCriteria();

        // 设置排序字段
//        processInfoExample.setOrderByClause("order_index asc");
//


        QueryWrapper<ProcessInfo> queryWrapper = new QueryWrapper<>();
        QueryWrapper<ProcessInfo> order_index = queryWrapper.orderByAsc("order_index");

        // 设置查询条件
        if (!StringUtil.isNullOrSpace(processInfo.getProcessName())) {
            queryWrapper.like("process_name",processInfo.getProcessName());
//            queryExampleCriteria.andProcessNameLike(SqlUtil.valueJoinLikeBoth(processInfo.getProcessName()));
        }
        if (!StringUtil.isNullOrSpace(processInfo.getProcessType())) {
            queryWrapper.eq("process_type",processInfo.getProcessType());
//            queryExampleCriteria.andProcessTypeEqualTo(processInfo.getProcessType());
        }

        // 执行查询
        IPage<ProcessInfo> processInfoIPage = processInfoMapper.selectPage(page, order_index);
//        PageInfo<ProcessInfo> pageResult = new PageInfo<>(processInfoIPage.getRecords());
//        pageResult.setTotal(processInfoIPage.getTotal());

        // pagehelper分页插件的问题，需要创建PageInfo才能获取总记录数，queryPage.getResult()和dbDataDictList是一样的
//        pageResult.setPages(processInfoIPage.getPages());
        // long pageResultTotal = pageResult.getTotal(); // 返回总数
        // List<DataDict> pageResultList = pageResult.getList(); // 返回当前的列表,pageInfoDataList=dbDataDictList
        // end 分页开始

        // 创建分页结果集对象
//        MyPageResult<ProcessInfo> myPageResult = MyPageResultUtil.createMyPageResultPlus(processInfoIPage);
        MyPageResult<ProcessInfo> myPageResult = MyPageResultUtil.createMyPageResultPlus(processInfoIPage);
        return myPageResult;
    }

    /**********************************
     * 用途说明: 根据id获取流程应用
     * 参数说明 processInfo
     * 返回值说明:
     ***********************************/
    @Override
    public ProcessInfo get(ProcessInfo processInfo) throws Exception {
        if(StringUtil.isNullOrSpace(processInfo.getId())) {
            throw new ScpException("params errror.");
        }
        ProcessInfo process = null;
        try {
            process = processInfoMapper.selectById(processInfo.getId());
        } catch (Exception e) {
            LOGGER.error("get.error;", e);
            throw e;
        }

        return process;
    }

    /**********************************
     * 用途说明: 根据id删除流程应用
     * 参数说明 ids
     * 返回值说明:
     ***********************************/
    @Override
    public int delete(List<String> ids) throws Exception {
        if(ids.size() == 0) {
            throw new ScpException("params errror.");
        }

        int updateRows = 0;

        try {
//            ProcessInfoExample processInfoExample = new ProcessInfoExample();
//            processInfoExample.createCriteria().andIdIn(ids);

//            QueryWrapper<ChangeProcessApply> queryWrapper = new QueryWrapper<>();
//            queryWrapper.in("id",activityInfoParams.getProcInstId());

            updateRows = processInfoMapper.deleteBatchIds(ids);
        } catch (Exception e) {
            LOGGER.error("delete.error;", e);
            throw e;
        }

        return updateRows;
    }

    /**********************************
     * 用途说明: 更新访问时间
     * 参数说明 processVisit
     * 返回值说明:
     ***********************************/
    @Override
    public int updateVisitTime(ProcessVisit processVisit) throws Exception {
        int updateRows = 0;

        if(StringUtil.isNullOrSpace(processVisit.getProcessFullName())) {
            throw new ScpException("params errror.");
        }

        try {
            UserInfo userinfo = currentUser.getCurrentUserDetail();

            QueryWrapper<ProcessVisit> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("process_full_name",processVisit.getProcessFullName());
            queryWrapper.eq("visit_user",userinfo.getUserId());
            List<ProcessVisit> processVisits = processVisitMapper.selectList(queryWrapper);
            if(processVisits.size()>0) {
                ProcessVisit updateProcessVisit = processVisits.get(0);
                updateProcessVisit.setVisitTime(new Date());
                updateProcessVisit.setProcessName(processVisit.getProcessName());
                updateRows = processVisitMapper.updateById(updateProcessVisit);
            }else{
                processVisit.setId(IDHelper.uuid());
                processVisit.setVisitTime(new Date());

                processVisit.setVisitUser(userinfo.getUserId());
                processVisit.setVisitUserName(userinfo.getUserName());
                updateRows = processVisitMapper.insert(processVisit);
            }

        } catch (Exception e) {
            LOGGER.error("save.error;", e);
            throw e;
        }

        return updateRows;
    }

    /**********************************
     * 用途说明: 分页最近访问流程
     * 参数说明
     * 返回值说明:
     ***********************************/
    @Override
    public MyPageResult<ProcessVisit> loadVisitPaging(ProcessVisit processVisit) {
        int pageNum = processVisit.getPageNum();
        int pageSize = processVisit.getPageSize();
        Page<ProcessVisit> page = new Page<>(pageNum, pageSize);

        QueryWrapper<ProcessVisit> queryWrapper = new QueryWrapper<>();
        QueryWrapper<ProcessVisit> order_index = queryWrapper.orderByDesc("visit_time");

        IPage<ProcessVisit> processInfoIPage = processVisitMapper.selectPage(page, order_index);

        MyPageResult<ProcessVisit> myPageResult = MyPageResultUtil.createMyPageResultPlus(processInfoIPage);
        return myPageResult;
    }
}
